package com.wtwd.campus.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.campus.dao.AttendanceRuleMapper;
import com.wtwd.campus.dao.StudentMapper;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.service.AttendanceRulesService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AttendanceRulesServiceImpl implements AttendanceRulesService {

    @Autowired
    private AttendanceRuleMapper attendanceRuleMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public int addAttendanceRule(AttendanceRulesVO data) {
        //先添加考勤规则信息
        int i = attendanceRuleMapper.addAttendanceRuleMess(data);
        if (i > 0) {
            List<Map<String, Object>> weekData = data.getDataList();
            if (data.getIfSync() == 1) {
                //同步添加
                Map<String, Object> map = weekData.get(0);
                for (int j = 2; j <= 7; j++) {
                    Map<String, Object> data2 = new HashMap<>(map);
                    data2.put("weekday", j);
                    weekData.add(data2);
                }
            }
            //添加每天的打卡时间信息
            int i1 = attendanceRuleMapper.addWeekDayMess(data.getId(), weekData);
            return i1;
        }
        return 0;
    }

    @Override
    public boolean judgeAttendanceRuleName(String name, Integer schoolId) {
        Map<String, Object> map = attendanceRuleMapper.judgeAttendanceRuleName(name, schoolId);
        return map == null ? true : false;
    }

    @Override
    public Map<String, Object> getAttendanceRulesList(Integer schoolId, Integer currPage, Integer pageSize) {
        //查询考勤信息
        List<AttendanceRulesVO> rulesList = attendanceRuleMapper.getAttendanceRulesBySchoolId(schoolId);
        List<Integer> idList = new ArrayList<>();
        rulesList.stream().forEach(e -> {
            idList.add(e.getId());
        });
        if (idList.size() == 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("total", rulesList.size());
            map.put("data", rulesList);
            return map;
        }
        //根据考勤信息id查找对应的每日考勤规则信息
        List<WeekDayRule> weekDayList = attendanceRuleMapper.getWeekDayListByIdList(idList);
        rulesList.stream().forEach(e -> {
            List<WeekDayRule> list = new ArrayList<>();
            weekDayList.stream().filter(j -> j.getId() == e.getId()).sorted(Comparator.comparing(WeekDayRule::getWeekday)).forEach(k -> {
                if (k.getLeaveAfternoonSelect() != 0 || k.getLeaveMorningSelect() != 0 || k.getSignAfternoonSelect() != 0 || k.getSignMorningSelect() != 0) {
                    //只有这一天有设置签到或者签退才加进去
                    list.add(k);
                }
            });
            e.setWeekDayRuleList(list);
        });
        //处理数据成分页
        currPage = currPage == 0 || currPage == 1 ? 1 : currPage;
        int start = (currPage - 1) * pageSize;
        int end = start + pageSize;
        List<AttendanceRulesVO> resultList = new ArrayList<>();
        for (int i = start; i < end; i++) {
            if (i >= rulesList.size()) {
                break;
            }
            resultList.add(rulesList.get(i));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", rulesList.size());
        map.put("data", resultList);
        return map;
    }

    @Override
    public AttendanceRulesVO getAttendanceRulesById(Integer id) {
        //查询考勤信息
        AttendanceRulesVO rule = attendanceRuleMapper.getAttendanceRulesById(id);
        //根据考勤信息id查找对应的每日考勤规则信息
        List<Integer> list = new ArrayList<>();
        list.add(rule.getId());
        List<WeekDayRule> weekDayList = attendanceRuleMapper.getWeekDayListByIdList(list);
        rule.setWeekDayRuleList(weekDayList);
        return rule;
    }

    @Override
    public int modifyAttendanceRules(AttendanceRulesVO data) {
        //修改考勤信息
        int i = attendanceRuleMapper.modifyAttendanceRules(data);
        //删除每日打卡信息
        int i1 = attendanceRuleMapper.deleteWeekDayRule(data.getId());
        //新增每日打卡信息
        List<Map<String, Object>> weekData = data.getDataList();
        if (data.getIfSync() == 1) {
            //同步添加
            Map<String, Object> map = weekData.get(0);
            for (int j = 2; j <= 7; j++) {
                Map<String, Object> data2 = new HashMap<>(map);
                data2.put("weekday", j);
                weekData.add(data2);
            }
        }
        //添加每天的打卡时间信息
        int i2 = attendanceRuleMapper.addWeekDayMess(data.getId(), weekData);
        return i + i1 + i2;
    }

    @Override
    public int deleteAttendanceById(Integer id) {
        //删除考勤信息
        int i = attendanceRuleMapper.deleteAttendanceById(id);
        //删除每日打卡信息
        int i1 = attendanceRuleMapper.deleteWeekDayRule(id);
        return i + i1;
    }

    @Override
    public Map<String, Object> getAttendanceSetBySchoolId(Integer schoolId, Integer currPage, Integer pageSize) {
        Page<Map<String, Object>> page = new Page<>(currPage, pageSize);
        IPage<Map<String, Object>> data = attendanceRuleMapper.getAttendanceSetBySchoolId(schoolId, page);
        Map<String, Object> result = new HashMap<>();
        result.put("total", data.getTotal());
        result.put("data", data.getRecords());
        return result;
    }

    @Override
    public Map<String, Object> getAttendanceSetByGradeId(Integer gradeId, Integer currPage, Integer pageSize) {
        Page<Map<String, Object>> page = new Page<>(currPage, pageSize);
        IPage<Map<String, Object>> data = attendanceRuleMapper.getAttendanceSetByGradeId(gradeId, page);
        Map<String, Object> result = new HashMap<>();
        result.put("total", data.getTotal());
        result.put("data", data.getRecords());
        return result;
    }

    @Override
    public List<Map<String, Object>> getUnBindingGradeBySchoolId(Integer schoolId) {
        return attendanceRuleMapper.getUnBindingGradeBySchoolId(schoolId);
    }

    @Override
    public List<Map<String, Object>> getRulesBySchoolId(Integer schoolId) {
        return attendanceRuleMapper.getRulesBySchoolId(schoolId);
    }

    @Override
    public int addAttendanceSetting(AttendanceSetting data) {
        return attendanceRuleMapper.addAttendanceSetting(data);
    }

    @Override
    public int modifyAttendanceSetting(AttendanceSetting data) {
        return attendanceRuleMapper.modifyAttendanceSetting(data);
    }

    @Override
    public int modifyAttendanceSetFlag(AttendanceSetting data) {
        return attendanceRuleMapper.modifyAttendanceSetFlag(data);
    }

    @Override
    public int deleteAttendanceSetting(Integer id) {
        return attendanceRuleMapper.deleteAttendanceSetting(id);
    }

    @Override
    public Map<String, Object> getAttendanceRecordList(AttendanceRecordVO data) {
        Page<Map<String, Object>> page = new Page<>(data.getCurrPage(), data.getPageSize());
        //条件筛选考勤记录
        if (data.getTime().equals(data.getMaxTime())) {
            data.setMaxTime(data.getTime() + 60 * 60 * 24 * 1000);
        }
        IPage<Map<String, Object>> result = attendanceRuleMapper.getAttendanceRecordList(data, page);
        Map<String, Object> map = new HashMap<>();
        map.put("total", result.getTotal());
        map.put("data", result.getRecords());
        return map;
    }

    @Override
    public List<ExportAttendanceRecord> getExportRecordList(AttendanceRecordVO data) {
        List<Map<String, Object>> exportRecordList = attendanceRuleMapper.getExportRecordList(data);
        List<ExportAttendanceRecord> list = new ArrayList<>();
        exportRecordList.stream().forEach(e -> {
            ExportAttendanceRecord record = new ExportAttendanceRecord();
            record.setId((Integer) e.get("id"));
            record.setClassName((String) e.get("classes_name"));
            record.setGradeName((String) e.get("grade_name"));
            record.setLeaveAfternoon(convertStatus((Integer) e.get("leave_afternoon")));
            record.setLeaveMorning(convertStatus((Integer) e.get("leave_morning")));
            record.setRfid((String) e.get("rfid"));
            record.setSignAfternoon(convertStatus((Integer) e.get("sign_afternoon")));
            record.setSignMorning(convertStatus((Integer) e.get("sign_morning")));
            record.setStuName((String) e.get("student_name"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            record.setTime(sdf.format(new Date((Long) e.get("time"))));
            list.add(record);
        });
        return list;
    }

    @Override
    public int saveAttendanceMetaRecordList(List<Map<String, Object>> list) {
        return attendanceRuleMapper.saveAttendanceMetaRecordList(list);
    }

    @Override
    public Map<String, Object> getRulesByCondition(Integer weekDay, Integer schoolId,Integer gradeId) {
        return attendanceRuleMapper.getRulesByCondition(weekDay, schoolId,gradeId);
    }

    @Override
    public AttendanceRecordData getAttendanceRecordByCondition(Long time, Integer stuId) {
        return attendanceRuleMapper.getAttendanceRecordByCondition(time, stuId);
    }

    @Override
    public int addAttendanceRecord(List<AttendanceRecordData> list) {
        return attendanceRuleMapper.addAttendanceRecord(list);
    }

    @Override
    public int modifyAttendanceRecord(List<AttendanceRecordData> list) {
        return attendanceRuleMapper.modifyAttendanceRecord(list);
    }

    @Override
    public List<Map<String, Object>> getNoRecordStuIdList(Integer week, Integer status, Long time) {
        return attendanceRuleMapper.getNoRecordStuIdList(week, status, time);
    }

    @Override
    public List<Integer> getRecordStuIdList(Integer week, Integer status, Long time) {
        return attendanceRuleMapper.getRecordStuIdList(week, status, time);
    }

    @Override
    public int getAttendanceSetCountByRuleId(Integer ruleId) {
        return attendanceRuleMapper.getAttendanceSetCountByRuleId(ruleId);
    }

    @Override
    public List<Map<String, Object>> getPushMess(List<Integer> stuIdList) {
        return attendanceRuleMapper.getPushMess(stuIdList);
    }

    @Override
    public List<Map<String, Object>> getNormalRecordPushMess(Long time, Integer status) {
        return attendanceRuleMapper.getNormalRecordPushMess(time, status);
    }

    @Override
    public List<Map<String, Object>> getBeLateRecordPushMess(Long time, Integer status) {
        return attendanceRuleMapper.getBeLateRecordPushMess(time, status);
    }

    @Override
    public List<Map<String, Object>> getLeaveEarlyRecordPushMess(Long time, Integer status) {
        return attendanceRuleMapper.getLeaveEarlyRecordPushMess(time, status);
    }

    @Override
    public List<Map<String, Object>> getWxAttendanceRecordList(Integer classId, Long time, Integer type, Integer status) {
        List<Map<String, Object>> list = attendanceRuleMapper.getWxAttendanceRecordList(classId, time, type, status);
        list.stream().forEach(e -> {
            if (e.get("time") == null) {
                e.put("time", "");
            } else {
                Long time1 = (long) e.get("time");
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                e.put("time", sdf.format(time1));
            }
        });
        return list;
    }

    @Override
    public List<Map<String, Object>> getWxUnRecordList(Long time, Integer classId,Integer type) {
        return attendanceRuleMapper.getWxUnRecordList(time, classId, type);
    }

    @Override
    public int judgeIfSetRule(Integer week, Integer classId, Integer type) {
        return attendanceRuleMapper.judgeIfSetRule(week, classId, type);
    }

    @Override
    public List<Map<String, Object>> getStudentAttendanceRecord(Integer classId, Long time) {
        return studentMapper.getStudentAttendanceRecord(classId, time);
    }

    /**
     * 转换打卡状态
     *
     * @param i
     * @return
     */
    public String convertStatus(Integer i) {
        String result = "";
        switch (i) {
            case 0:
                result = "正常";
                break;
            case 1:
                result = "未打卡";
                break;
            case 2:
                result = "迟到";
                break;
            case 3:
                result = "早退";
                break;
            case 4:
                result = "";
                break;
        }
        return result;
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        List<Integer> list2 = new ArrayList<>();
        list2.add(3);
        list2.add(4);
        list.stream().forEach(e -> {
            System.out.println(e);
            list2.stream().forEach(j -> {
                System.out.println(j + "," + e);
            });
        });
    }


}
